#include "BulletObject.h"
#include "2d\CCActionInterval.h"
#include "math\Vec2.h"
#include "cocos2d.h"
#include "2d\CCActionInstant.h"
#include "SpriteMaker.h"

BulletObject::BulletObject(b2World *_World) :BaseObject(_World)
{
}


BulletObject::~BulletObject()
{
}

void BulletObject::init(SpriteBatchNode* _Spritebatch, SpriteFrameCache* _Cache)
{
	mId = OBJECT_BULLET;
	mBody = new BulletBody(mWorld, b2_dynamicBody);
	mBody->setPosition(b2Vec2(200, 400));
	mBody->mColBody->SetUserData(this);

	mSprite = SpriteMaker::makeSprite(_Spritebatch, "bullet_01.png");

	mAnimation = SpriteMaker::makeAnimation(_Cache, "bullet", 1, 4, 1.f);
	mSprite->runAction(mAnimation);
	mBody->setAngle(3.14f);
	mSprite->setScale(0);
	mIsAction = false;
	mIsCollision = false;
}

void BulletObject::update(float dt)
{
	draw();
}

void BulletObject::draw()
{
	if (mIsAction == false)
	{
		mSprite->setPosition(Vec2(mBody->getPosition().x, mBody->getPosition().y));
		mSprite->setRotation(mBody->getAngle()*-Define::RAD_TO_DEG);
	}
	else
	{
		mBody->setPosition(b2Vec2(mSprite->getPosition().x, mSprite->getPosition().y));
		mBody->setAngle(mSprite->getRotation()*-Define::DEG_TO_RAD);
	}
	
}

void BulletObject::destroy()
{

}

void BulletObject::onCollisionWith(BaseObject *_Object)
{
	switch (_Object->mId)
	{
	case OBJECT_GUN:
		if (mIsCollision == false)
		{
			mIsAction = true;
			mIsCollision = true;

			auto action = MoveTo::create(0.5f, Vec2(_Object->mBody->getPosition().x, _Object->mBody->getPosition().y));
			auto sequence = Sequence::create(action, moveToCenterCallBack(_Object), NULL);
			mSprite->runAction(sequence);
		}
		break;

	}
	
}

CallFunc * BulletObject::moveToCenterCallBack(BaseObject *_Object)
{
	return CallFunc::create([_Object, this](){
		float alpha = _Object->mBody->getAngle()*-Define::RAD_TO_DEG;
		if (alpha > 360)
		{
			alpha = alpha - ((int)alpha / 360)*360;
		}
		auto action = RotateTo::create(0.1f, alpha);
		auto sequence = Sequence::create(action, rotateSameCallBack(_Object), NULL);
		mSprite->runAction(sequence);

	});
}

CallFunc * BulletObject::rotateSameCallBack(BaseObject *_Object)
{
	return CallFunc::create([_Object, this](){
		float x, y, alpha;
		alpha = _Object->mBody->getAngle();
		x = 40 * std::sin(alpha);
		y = 40 * std::cos(alpha);
		auto action = MoveTo::create(0.5f, Vec2(_Object->mBody->getPosition().x - x, _Object->mBody->getPosition().y + y));
		auto sequence = Sequence::create(action, moveToFightCallBack(_Object), NULL);
		mSprite->runAction(sequence);
	});
}

CallFunc * BulletObject::moveToFightCallBack(BaseObject *_Object)
{
	return CallFunc::create([_Object, this](){
		mIsAction = false;
		_Object->onCollisionWith(this);
		mCanFight = true;

	});
}

